package seace.services;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seace.model.Certificado;
import seace.model.Participante;
import seace.utils.Constants;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class GeraCertificados implements Service {

	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String cpf = request.getParameter("cpf");
		String action = request.getParameter("action");

		if (action != null) {
			if (action.equals(Constants.UM)) {
				try {
					// ParticipanteDao dao = new ParticipanteDao();
					// dao.getParticipanteFromInscricao();
					Participante participante;
					participante = new Participante();
					participante.setCpf(cpf);
					participante.setNome("Benevid Felix da Silva");

					getCertificadoParticipante(request, response, participante);

				} catch (Exception e) {
					PrintWriter out = response.getWriter();
					out.print("Não foi possível fazer consulta a base de dados!");
				}

			}
		} else {
			PrintWriter out = response.getWriter();
			out.print("Inscrição Invalida!");
		}
	}
	private void getCertificadoParticipante(HttpServletRequest request,
			HttpServletResponse response,Participante participante) throws IOException {
		Certificado certificado = new Certificado();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {

			/*
			 * Verso do Certificado
			 */
			
			PdfWriter writer = PdfWriter.getInstance(certificado, baos);

			certificado.addTitle("Sistema de Credenciamento");
			certificado.addAuthor("Unemat/Colider-MT");

			certificado.open();

			Image img = Image.getInstance("basecertificado.png");
			img.scaleToFit(PageSize.A4.rotate().getWidth(), PageSize.A4.rotate().getHeight());
			img.setAbsolutePosition(0, 0);

			BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
					BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

			PdfContentByte under, over;
			under = writer.getDirectContentUnder();
			over = writer.getDirectContent();

			under.addImage(img);
			
			ColumnText ct = new ColumnText(over);
	
			Chunk ch1 = new Chunk();
			ch1.setFont(new Font(bf, 18));
			ch1.append("Certificamos que ");
			
			Chunk nome = new Chunk();
			nome.append(participante.getNome());
			nome.setFont(new Font(bf, 18, Font.BOLD));
			
			Chunk evento = new Chunk();
			evento.setFont(new Font(bf, 18));
			evento.append("V Semana Acadêmica de Computação Educacional e II Semana Acadêmica de Administração");
			
			Chunk ch2 = new Chunk();
			ch2.setFont(new Font(bf, 18));
			ch2.append(" participou da "+ evento.getContent()+", realizada no Campus Universitário do Vale do Teles Pires" +
					" - Unemat/Colider, no periodo de 28/06 a 02/07 de 2010.");
			
			Phrase frase = new Phrase();
			//frase.setLeading(10);
			frase.add(ch1);
			//frase.setLeading(10);
			frase.add(nome);
			//frase.setLeading(10);
			frase.add(ch2);
			
			Paragraph p = new Paragraph(frase);
			p.setLeading(25);
			p.setAlignment(Element.ALIGN_JUSTIFIED);

			ct.addElement(p);
			
			ct.setSimpleColumn(130, 320, 720, 170);
			ct.go();

			/*
			 * Verso do Certificado
			 */
			certificado.newPage();
			
//			over.beginText();
//			over.setFontAndSize(bf, 18);
//			over.setTextMatrix(60, 80);
//			over.showText("---");
//			over.endText();
			
			
			Chunk cronograma = new Chunk();
			cronograma.setFont(new Font(bf, 18));
			cronograma.append("Cronograma");
			
			
			Phrase texto_frase = new Phrase();
			//frase.setLeading(10);
			texto_frase.add(cronograma);
			
			Paragraph p2 = new Paragraph(texto_frase);
			p2.setLeading(25);
			p2.setAlignment(Element.ALIGN_JUSTIFIED);

			ct.addElement(p2);
			
			ct.setSimpleColumn(130, 320, 720, 170);
			ct.go();
		
			
			
			
			certificado.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		

		// setting some response headers
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control",
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");
		// setting the content type
		response.setContentType("application/pdf");
		// the contentlength is needed for MSIE!!!
		response.setContentLength(baos.size());
		// write ByteArrayOutputStream to the ServletOutputStream
		response.setHeader("Content-Disposition",
				"attachment; filename=\"certificado.pdf\"");
		ServletOutputStream out = response.getOutputStream();
		baos.writeTo(out);
		out.flush();
	}

}
